package com.laikan.reader.bookfriend.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.telephony.TelephonyManager;
import android.text.format.Formatter;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewTreeObserver;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import com.laikan.library.components.activitys.BasicActivity;
import com.laikan.library.helpers.BasicEvent;
import com.laikan.library.managers.ToastMgr;
import com.laikan.library.utils.SPUtil;
import com.laikan.reader.R;
import com.laikan.reader.core.events.LaiKanEvent;
import com.laikan.reader.core.utils.PublicUtil;
import com.umeng.analytics.MobclickAgent;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

import static com.laikan.reader.apirequester.FindPwdRequester.*;

/**
 * 找回密码页
 *
 * @author wxl
 */
public class FindPswActivity extends BasicActivity implements OnClickListener {

    private int width, height;
    private Bitmap back_tv_bitmap, bitmap;
    private ImageView back_tv;
    private TelephonyManager tm;
    private String ip = null;
    private TextView resigter_first, resigter_second, resigter_third, get_yz_tv, submit_yz_tv, resigter_tv;
    private LinearLayout lin_first, lin_second, lin_third;
    private EditText resigter_number, yz_number, et_password_new, et_password_confirm;
    private String phone_number, code, mPasswordNew, mPasswordsConfirm;
    private RelativeLayout back_layout;

    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void assignViews() {
        setContentView(R.layout.lk_findpsw);
        ViewTreeObserver vto1 = back_tv.getViewTreeObserver();
        vto1.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                back_tv.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                width = back_tv.getWidth();
                height = back_tv.getHeight();
                back_tv_bitmap = PublicUtil.getAlphaBitmap(PublicUtil.readBitMap(mContext, R.drawable.lk_back_small), Color.parseColor("#66ccdd"));
                bitmap = PublicUtil.resizeBitmap(back_tv_bitmap, width, height);
                back_tv.setImageBitmap(bitmap);
            }
        });
        back_layout = (RelativeLayout)findViewById(R.id.back_layout);
        back_tv = (ImageView)findViewById(R.id.iv_back);
        resigter_first = (TextView)findViewById(R.id.tv_resigter_first);
        resigter_second = (TextView)findViewById(R.id.tv_resigter_second);
        resigter_third = (TextView)findViewById(R.id.tv_resigter_third);
        lin_first = (LinearLayout)findViewById(R.id.lin_first);
        lin_second = (LinearLayout)findViewById(R.id.lin_second);
        lin_third = (LinearLayout)findViewById(R.id.lin_third);
        resigter_number = (EditText)findViewById(R.id.et_resigter_number);
        get_yz_tv = (TextView)findViewById(R.id.tv_get_yz_tv);
        yz_number = (EditText)findViewById(R.id.et_yz_number);
        submit_yz_tv = (TextView)findViewById(R.id.btn_submit_yz_tv);
        et_password_new = (EditText)findViewById(R.id.et_password_new);
        et_password_confirm = (EditText)findViewById(R.id.et_password_confirm);
        resigter_tv = (TextView)findViewById(R.id.tv_resigter);
    }

    @SuppressWarnings ({"deprecation", "static-access"})
    @Override
    protected void initData() {
        // 设置找回密码 第一步
        setStep(1);
        tm = (TelephonyManager)getSystemService(mContext.TELEPHONY_SERVICE);
        WifiManager wifiManager = (WifiManager)getSystemService(WIFI_SERVICE);
        WifiInfo info = wifiManager.getConnectionInfo();
        ip = Formatter.formatIpAddress(info.getIpAddress());

        if ("0.0.0.0".equals(ip)) {
            ip = getLocalIpAddress();
        }
    }

    /**
     * 获取ip地址
     *
     * @return
     */
    public String getLocalIpAddress() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()) {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        }catch (SocketException ex) {
        }
        return null;
    }

    @Override
    protected void setListener() {
        resigter_tv.setOnClickListener(this);
        back_layout.setOnClickListener(this);
        submit_yz_tv.setOnClickListener(this);
        get_yz_tv.setOnClickListener(this);
        resigter_number.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                InputMethodManager imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
                if (!hasFocus) {
                    imm.hideSoftInputFromWindow(resigter_number.getWindowToken(), 0);
                }
            }
        });
        yz_number.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                InputMethodManager imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
                if (!hasFocus) {
                    imm.hideSoftInputFromWindow(resigter_number.getWindowToken(), 0);
                }
            }
        });
    }

    /**
     * 找回密码步骤 设置
     *
     * @param i
     */
    private void setStep(int i) {
        switch (i) {
            case 1:
                lin_first.setVisibility(View.VISIBLE);
                lin_second.setVisibility(View.GONE);
                lin_third.setVisibility(View.GONE);
                resigter_first.setTextColor(getResources().getColor(R.color.C_66ccdd));
                resigter_second.setTextColor(getResources().getColor(R.color.C_999999));
                resigter_third.setTextColor(getResources().getColor(R.color.C_999999));
                break;
            case 2:
                lin_first.setVisibility(View.GONE);
                lin_second.setVisibility(View.VISIBLE);
                lin_third.setVisibility(View.GONE);
                resigter_first.setTextColor(getResources().getColor(R.color.C_999999));
                resigter_second.setTextColor(getResources().getColor(R.color.C_66ccdd));
                resigter_third.setTextColor(getResources().getColor(R.color.C_999999));
                break;
            case 3:
                lin_first.setVisibility(View.GONE);
                lin_second.setVisibility(View.GONE);
                lin_third.setVisibility(View.VISIBLE);
                resigter_first.setTextColor(getResources().getColor(R.color.C_999999));
                resigter_second.setTextColor(getResources().getColor(R.color.C_999999));
                resigter_third.setTextColor(getResources().getColor(R.color.C_66ccdd));
                break;

            default:
                break;
        }
    }

    @Override
    protected void parseEvent(BasicEvent event) {
        switch (event.getEventID()) {
            case LaiKanEvent.EVENT_ID_RESET_PASSWORD:
                SPUtil.putString("psdString", mPasswordNew + "/" + phone_number);
                Intent intent = new Intent(mContext, LoginActivity.class);
                startActivity(intent);
                Intent intent1 = new Intent();
                setResult(8, intent1);
                finish();
                break;
            case LaiKanEvent.EVENT_ID_GET_VERIFY_CODE:
                setStep(2);
                break;
            case LaiKanEvent.Event_ID_CHECK_VERIFY_CODE:
                setStep(3);
                break;
            default:
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_submit_yz_tv: //提交验证码
                code = yz_number.getText().toString().trim();
                checkVerifyCode(code, phone_number);
                break;
            case R.id.tv_get_yz_tv:  //获取验证码
                phone_number = resigter_number.getText().toString().trim();
                String deviceId = tm.getDeviceId();
                getYz(phone_number, deviceId);
                break;
            case R.id.tv_resigter: //修改密码
                mPasswordNew = et_password_new.getText().toString().trim();
                mPasswordsConfirm = et_password_confirm.getText().toString().trim();
                if (mPasswordNew.length() == 0) {
                    ToastMgr.showShortToast("密码不能为空");
                }else if (mPasswordsConfirm.length() == 0) {
                    ToastMgr.showShortToast("密码不能为空");
                }else if (!mPasswordsConfirm.equals(mPasswordNew)) {
                    ToastMgr.showShortToast("两次密码不一致");
                }else {
                    forget(mPasswordNew, mPasswordsConfirm, phone_number, code);
                }
                break;
            case R.id.back_layout:  //返回键找回密码
                resigter_number.clearFocus();
                finish();
                break;
            default:
                break;
        }
    }
}
